package com.lagou.filter;

import com.lagou.task.TPMonitorTask;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author bobcheng
 * @date 2020/6/16
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    private static final ScheduledExecutorService REPORT_WORKER = Executors.newScheduledThreadPool(1);

    public TPMonitorFilter() {
        REPORT_WORKER.scheduleWithFixedDelay(TPMonitorTask.getInstance(), 0, 5, TimeUnit.SECONDS);
    }

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            return invoker.invoke(invocation);
        } finally {
            System.out.println(invocation.getMethodName() + " invoke time:" + (System.currentTimeMillis() - startTime) + "毫秒");
            long costTime = System.currentTimeMillis() - startTime;
            TPMonitorTask.saveCost(costTime, invocation.getServiceName(), invocation.getMethodName());
        }
    }



}
